package com.fenghongzhang.day015;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.ContentResolver;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 1,清单授权
 * 2,动态授权
 * 3,同不同意
 * 4,内容解析者去sd卡查询所有歌曲.
 */
public class MainActivity extends AppCompatActivity {

    private Button play;
    private Button pause;
    private Button restart;
    private Button stop;
    private ListView lv;

    private int index = 0;
    private SeekBar seekBar;

    //播放模式
    private int playModel = 0;

    private TextView title;
    private TextView atrist;
    private Timer timer;
    private List<Music> list;
    private MediaPlayer mediaPlayer = new MediaPlayer();//idle
    private Button model;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        model = (Button) findViewById(R.id.model);
        title = (TextView) findViewById(R.id.title);
        atrist = (TextView) findViewById(R.id.atrist);
        lv = (ListView) findViewById(R.id.lv);
        //最大值,和进度值
        seekBar = (SeekBar) findViewById(R.id.seekBar);
        pause = (Button) findViewById(R.id.pause);
        restart = (Button) findViewById(R.id.restart);
        stop = (Button) findViewById(R.id.stop);



        //请求权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 100);
        }

        //lv的点击事件
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                index = position;
                play(position);
            }
        });

        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            /**
             *
             * @param seekBar
             * @param progress 进度值
             * @param fromUser 是否用户拖动
             */
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if(fromUser){
                    mediaPlayer.seekTo(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

    }

    //播放的逻辑
    private void play (int position){
        mediaPlayer.reset();
        ///storage/emulated/0/Music/Jam - 七月上.mp3
        try {
            mediaPlayer.setDataSource(list.get(position).getData());
            mediaPlayer.prepareAsync();
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mediaPlayer.start();
                }
            });

            //播放完成回调
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    //在这里选择是单曲,还是随机,还是顺序.
                    switch (playModel){
                        case MusicUtil.PLAY_MODEL_SINGLE:
                            play(index);
                            break;
                        case MusicUtil.PLAY_MODEL_RANDOM:
                            //随机
                            int i = new Random().nextInt(list.size());
                            play(i);
                            break;
                        case MusicUtil.PLAY_MODEL_ORDER:
                            playNext();
                            break;
                    }
                }
            });


            //设置歌曲名和歌手
            title.setText(list.get(position).getTitle());
            atrist.setText(list.get(position).getArtist());

//            seekBar.setProgress(?);
            if (timer == null) {
                timer = new Timer();
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        //在第一个播放这个音乐,赋值最大值
                        seekBar.setMax(mediaPlayer.getDuration());
                        //进度值
                        seekBar.setProgress(mediaPlayer.getCurrentPosition());
                    }
                }, 0, 1000);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
        @Override
        public void onRequestPermissionsResult ( int requestCode, @NonNull String[] permissions,
        @NonNull int[] grantResults){
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            if (requestCode == 100 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //直接去sd卡取到数据源
                ContentResolver contentResolver = getContentResolver();
                Cursor query = contentResolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
                //list
                list = new ArrayList<>();
                if (query != null) {
                    while (query.moveToNext()) {
                        String title = query.getString(query.getColumnIndex(MediaStore.Audio.Media.TITLE));
                        String artist = query.getString(query.getColumnIndex(MediaStore.Audio.Media.ARTIST));
                        String duration = query.getString(query.getColumnIndex(MediaStore.Audio.Media.DURATION));
                        String size = query.getString(query.getColumnIndex(MediaStore.Audio.Media.SIZE));
                        String data = query.getString(query.getColumnIndex(MediaStore.Audio.Media.DATA));//
                        String albumId = query.getString(query.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));

                        //如果时间较短,就不加了
                        if(Integer.parseInt(duration) > 1000 * 60){
                            Music music = new Music(title, artist, duration, data, size, albumId);
                            list.add(music);
                        }


                    }
                    query.close();
                    //创建适配器.
                    MusicAdapter musicAdapter = new MusicAdapter(this, list);
                    lv.setAdapter(musicAdapter);
                }
            } else {
                //
            }
        }


        public void pause (View view){
            //暂停
            mediaPlayer.pause();
        }

        public void restart (View view){
            mediaPlayer.start();
        }

        public void stop (View view){
            mediaPlayer.stop();
        }

        //上一首
        public void pre (View view){

            if (--index <= 0) {
                index = list.size() - 1;
            }
            play(index);

        }

        public void next (View view){
            playNext();
        }

    private void playNext() {
        if (++index > list.size()-1) {
            index = 0;
        }
        play(index);
    }

    //改变播放模式
    public void model(View view) {
        //弹出窗口
        final PopupWindow popupWindow = new PopupWindow();
        popupWindow.setWidth(200);
        popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);

        View inflate = LayoutInflater.from(this).inflate(R.layout.pop_layout, null);
        TextView single = inflate.findViewById(R.id.pop_single);
        single.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "单曲", Toast.LENGTH_SHORT).show();
                playModel = MusicUtil.PLAY_MODEL_SINGLE;
                popupWindow.dismiss();
            }
        });

        TextView random = inflate.findViewById(R.id.pop_random);
        random.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                playModel = MusicUtil.PLAY_MODEL_RANDOM;
                Toast.makeText(MainActivity.this, "随机", Toast.LENGTH_SHORT).show();
                popupWindow.dismiss();
            }
        });


        TextView order = inflate.findViewById(R.id.pop_order);
        order.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                playModel = MusicUtil.PLAY_MODEL_ORDER;
                Toast.makeText(MainActivity.this, "顺序", Toast.LENGTH_SHORT).show();
                popupWindow.dismiss();
            }
        });

        //添加内容
        popupWindow.setContentView(inflate);

        //点击外部pop可以取消
        popupWindow.setOutsideTouchable(true);

        //在哪里显示
        popupWindow.showAsDropDown(model,0,-350);
    }
}

